<template>
  <div class="wraps">
    <div ref="bar" class="bar"></div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
let speed = 1;
let bar = ref<HTMLElement>();
let timer = 0;

const startLoading = () => {
  let barDom = bar.value as HTMLElement;
  speed = 1;
  // requestAnimationFrame 返回一个id
  timer = window.requestAnimationFrame(function fn() {
    if (speed < 90) {
      speed++;
      barDom.style.width = speed + '%';
      window.requestAnimationFrame(fn); // 递归调用重复动画
    } else {
      speed = 1;
      window.cancelAnimationFrame(timer);
    }
  });
};
const endLoading = () => {
  let barDom = bar.value as HTMLElement;
  setTimeout(() => {
    window.requestAnimationFrame(() => {
      speed = 100;
      barDom.style.width = speed + '%';
      setTimeout(() => {
        barDom.style.display = 'none';
      }, 100);
    });
  }, 2000);
};

defineExpose({
  startLoading,
  endLoading
});
</script>

<style lang="scss" scoped>
.wraps {
  position: fixed;
  top: 0;
  width: 100%;
  height: 20px;
  .bar {
    height: inherit;
    width: 0;
    background: rgb(255, 0, 0);
  }
}
</style>
